// components/table/index.js
import wxApiHandler from "../../model/wxApiHandler"
import {promisic} from "../../utils/util"
import {User} from "../../model/user"
import {Apply} from "../../model/apply"

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    score: Number
  },

  /**
   * 组件的初始数据
   */
  data: {
    showLoginBtn: false,
    showApplyBtn: false,
    name: null,
    score: 0
  },
  timer: null,
  lifetimes: {
    async attached() {
    }
  },

  pageLifetimes: {
    async show() {
      await this.loadAuthStatus()
      this.timer = setTimeout(async () => {
        const user = new User()
        if (user) {
          await this.loadApplyInfo()
        }
      }, 1000)
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    async loadApplyInfo() {
      clearTimeout(this.timer)
      const apply = wx.getStorageSync('apply')
      if (apply) {
        this.setData({
            name: apply.name,
            showApplyBtn: false
        })
      }else {
        const apply = await Apply.getApplyInfo()
        if (!apply) {
          this.setData({
            showApplyBtn: true
          })
        }else {
          wx.setStorageSync('apply', apply)
          this.setData({
            name: apply.name,
            showApplyBtn: false
          })
        }
      }
    },
    async loadAuthStatus() {
      const showLogin = !await this.hasAuthUserInfo()
      this.setData({
        showLoginBtn: showLogin
      })
    },
    async hasAuthUserInfo() {
      const setting = await promisic(wx.getSetting)()
      const userInfo = setting.authSetting['scope.userInfo']
      return !!userInfo
    },
    async getUserInfo(e) {
      if (e.detail.userInfo) {
        const user = new User()
        await user.updateUserInfo({
          source_name: e.detail.userInfo.nickName,
          source_avatar: e.detail.userInfo.avatarUrl
        })
        this.setData({
          showLoginBtn: false
        })
        this.loadApplyInfo()
      }
    },
    onApplyTap () {
      wx.navigateTo({
        url: '/pages/apply/apply'
      })
    },
    onRuleTap() {
      wx.navigateToMiniProgram({
        appId: 'wxaa426aa8aae392fc',
        path: 'pages/index/index',
        extraData: {},
        //develop 开发版; trial 体验版; release 正式版
        envVersion: 'release',
        success(res) {
          // 打开成功
        }
      })
    }
  }
})
